<template>
  <view class="com-shopping-cart">
    <!-- 遮罩层 禁用操作 -->
    <view v-if="isMask" class="shopping-cart-mask" @click.stop>
      <image class="mask-icon" src="/static/images//icons/icon-cup.svg" width="30rpx" height="30rpx" />
      <view> <text class="mask-txt"> 正在支付</text></view>

      <view class="mt-15rpx">
        <u-button type="primary" size="large" @click="cancelPay">继续点餐</u-button>
      </view>
    </view>

    <!-- 购物车 -->
    <view class="left-box h-full">
      <view class="merber-login">
        <!-- 会员登录按钮 -->
        <u-icon
          name="integral-fill"
          :label="merberInfo.customerName || '会员登录'"
          color="var(--kui-color-theme)"
          label-color="#5286eb"
          size="15rpx"
          label-size="10rpx"
          @click="onClickMemberLogin"
        ></u-icon>
      </view>
      <view class="order-list flex-auto">
        <view
          @click="orderItemClick(item)"
          v-for="(item, index) in orderItems"
          :key="index"
          :class="[currSelected.foodTypeId == item.foodTypeId ? 'active' : '', 'order-item']"
        >
          <view class="_item-name line-clamp-1 text-ellipsis">{{ item.name }}</view>
          <view class="_item-count">x{{ item.count }}</view>
          <view class="_item-price">￥{{ item.price }}</view>
        </view>

        <u-empty
          v-if="orderItems.length == 0"
          mode="data"
          text="空空如也~"
          :icon="'/static/images/state/state_no_shopping.png'"
          width="150rpx"
          height="150rpx"
        ></u-empty>
      </view>

      <!-- 结算操作 -->
      <view class="settlement p-5rpx">
        <view class="flex justify-between">
          <u-checkbox-group @change="onIsPackChange">
            <u-checkbox
              name="isPack"
              label="打包"
              size="12rpx"
              icon-size="10rpx"
              label-size="10rpx"
              active-color="var(--kui-color-theme)"
            ></u-checkbox>
          </u-checkbox-group>
          <view class="flex">
            <view class="total-count">共{{ orderItems.length }}项</view>
            <view class="total-price">￥{{ totalPrice }}</view>
          </view>
        </view>
        <view class="mt-5rpx">
          <u-button
            @click="goCollectPayment(item)"
            color="var(--kui-color-theme)"
            :disabled="orderItems.length == 0"
            :loading="loading"
            size="large"
            custom-style="border-radius: 4rpx;"
            >去收款
          </u-button>
        </view>
      </view>
    </view>
    <!-- 操作条 -->
    <view class="right-box">
      <template v-for="(item, index) in toolbar" :key="index">
        <view
          v-if="item.show ? item.show() : currSelected.count > 0"
          @click="toolbarItemClick(item)"
          class="toolbar-item relative"
          :style="{
            backgroundColor: item.bgColor || '#f5f5f5',
          }"
        >
          <view v-if="item.count && item.count() > 0" class="point">{{ item.count() }}</view>
          <u-icon v-if="item.icon" :name="item.name" bold size="10rpx"></u-icon>
          <text v-else>
            {{ getToolBarItemName(item) }}
          </text>
        </view>
      </template>
    </view>

    <!-- 悬浮的面板 -->
    <view class="panel" v-if="panelShow">
      <!-- 遮罩层 -->
      <view class="panel-mask" @click="closePanel"></view>

      <u-row gutter="0" customStyle="width:750rpx;">
        <u-col span="4">
          <view class="col-layout">
            <com-order-dialog ref="refOrderDialog" @close="closePanel" />
          </view>
        </u-col>
        <u-col span="4">
          <view class="col-layout bg-purple-dark"> </view>
        </u-col>
      </u-row>

      <u-row gutter="0" customStyle="width:750rpx;">
        <u-col span="8">
          <view class="col-layout not-shadow">
            <pay-order-dialog ref="refPayOrderDialog" @finish="onPayFinish" />
          </view>
        </u-col>
      </u-row>
    </view>

    <resultPopup ref="refCommonPopup">
      <template #default="{ result }">
        <view v-if="result.dataType == 'cash'" class="mt-20rpx flex-col items-center justify-center text-center">
          <text class="block text-base py-10rpx text-gray-400"> 找零 </text>
          <text class="block font-bold"> {{ result.giveChange || "0.00" }} 元 </text>
        </view>
        <comMerberPayInfo v-else-if="result.dataType == 'card' && result.merberInfo" :info="result.merberInfo" />
      </template>
      <template #confirm="{ config }">
        <view class="btns flex">
          <view class="btns-item" @click="refCommonPopup.close()">
            <text class="btns-item-txt"> 关闭 </text>
          </view>
          <view v-if="config.merberInfo" class="btns-item confirm" @click="clearMemberOfComPopup">
            <text class="btns-item-txt"> 清除会员信息 </text>
          </view>
        </view>
      </template>
    </resultPopup>
  </view>

  <nfc-popup ref="refNfcPopup" />

  <!-- 会员登陆弹窗 -->
  <merber-login-popup ref="refMerberLoginPopup" @confirm="onMerberLogin" />

  <common-popup ref="refPopup" @confirm="confirmPopup" />

  <!-- 会员信息弹窗 -->
  <resultPopup ref="refMerberInfoPopup" :show-icon="false">
    <template #default>
      <comMerberInfo :info="merberInfo" />
    </template>
    <template #confirm="{ config }">
      <view class="btns flex">
        <view class="btns-item" @click="refMerberInfoPopup.close()">
          <text class="btns-item-txt"> 关闭 </text>
        </view>
        <view class="btns-item confirm" @click="clearMember">
          <text class="btns-item-txt"> 清除会员信息 </text>
        </view>
      </view>
    </template>
  </resultPopup>
</template>
<script setup>
import { useStore } from "vuex";
import comOrderDialog from "./com-order-dialog.vue";
import PayOrderDialog from "./com-pay-dialog/com-pay-dialog.vue";
import { reactive, computed, ref, watch, onMounted, onBeforeUnmount, nextTick } from "vue";
import resultPopup from "@/components/common-popup/result-popup.vue";
import comMerberPayInfo from "./com-merber-pay-info.vue";
import comMerberInfo from "./com-merber-info.vue";
import { getBuffetOrderDetail, getBuffetOrderDetailByPrentId, getCustomerInfoByCard, netPrinterPrinting } from "@/api";
import dayjs from "dayjs";
import { printorder, printStart, printStartByDevice } from "@/pages/subReportForm/print-config/print-utils";
import { getDetailsByCustomerId } from "@/pages/subMember/utils";
import { formatMoney } from "@/utils/util";
import { openSubScreen, openSubScreenByParams } from "@/utils/sceeenUtils";

const refMerberInfoPopup = ref();

const refPopup = ref();
const store = useStore();

// 购物车页面状态
const isMask = ref(false);
// 监听状态通知主页面的搜索按钮禁用
watch(isMask, (newVal) => {
  uni.$emit("cart-page:mask-change", newVal);
});

const panelShow = ref(false);

// 购物车列表
const orderItems = reactive(store.getters.shoppingCart);

// 结算金额
const totalPrice = computed(() => {
  return orderItems.reduce((pre, cur) => pre + cur.price * cur.count, 0).toFixed(2);
});

// 监听购物车列表变化
watch(orderItems, (newVal) => {
  // 更新缓存
  store.commit("shoppingCard/setCardlist", newVal);
  // 更新客户屏
  openSubScreenByParams({
    mode: "standby-mode",
    money: totalPrice.value,
    action: "awite-pay",
    merberInfo: merberInfo.value,
  });
});

const refOrderDialog = ref();
const closePanel = () => {
  panelShow.value = false;
};

const orderItemClick = (item) => {
  panelShow.value = true;
  // 延迟更新, 等待 panelShow 出来
  nextTick(() => {
    currSelected.value = item;
  });
};

// 当前选中商品
const currSelected = ref({});

// 监听当前选中商品变化
watch(currSelected, (newVal) => {
  // 注意 () => 变化会导致 newVal 结果变化，更改注意排查
  // console.log("当前选中", newVal.value);
  // 发送事件
  uni.$emit("cart-item:selected", newVal);
});

const toolbar = [
  {
    name: "清空",
    show: () => true,
    func: () => {
      orderItems.splice(0, orderItems.length);
      currSelected.value = {};
      closePanel();
      console.log("清空成功");
    },
  },
  {
    name: "plus",
    show: () => currSelected.value.count > 0,
    icon: true,
    func: () => {
      if (currSelected.value && currSelected.value.count) {
        currSelected.value.count++;
      }
    },
  },
  {
    name: () => currSelected.value.count,
    bgColor: "white",
    show: () => currSelected.value.count > 0,
  },
  {
    name: "minus",
    icon: true,
    show: () => currSelected.value.count > 0,
    func: () => {
      if (currSelected.value && currSelected.value.count) {
        if (currSelected.value.count > 1) {
          currSelected.value.count--;
        } else {
          uni.showToast({
            icon: "none",
            title: "已经是最后一道菜了",
            duration: 2000,
          });
        }
      }
    },
  },
  // {
  //   name: "备注",
  //   show: () => currSelected.value.count > 0,
  //   func: () => {
  //     console.log("备注");
  //     // 自定义备注
  //     refRemarkPopup.value.open({
  //       title: "自定义备注",
  //       content: currSelected.value.remark,
  //       confirmText: "保存",
  //       cancelText: "取消",
  //     });
  //   },
  // },
  {
    name: "删除",
    func: () => {
      // 查找下标
      const index = orderItems.findIndex((item) => item.foodTypeId === currSelected.value.foodTypeId);
      orderItems.splice(index, 1);
      // 删除之后清空当前选择
      currSelected.value = {};
      closePanel();
    },
  },
  {
    name: "存单",
    show: () => true,
    func: () => {
      console.log("存单");
      store.commit("shoppingCard/setDepositReceipt", {
        isPack: isPack.value, // 是否打包
        useMember: !!merberInfo.value.customerName, // 是否登录会员
        member: merberInfo.value || {}, // 会员信息 useMember = true 时使用,
        productList: [...orderItems], // 商品列表 (...orderItems 取消其引用特性)
        // saveTime: dayjs().format("YYYY/MM/DD HH:mm:ss"), // 存单时间
      });
      refCommonPopup.value.open({
        title: "存单完成",
        closeInAfter: 10000,
        content: "当前购物车商品已保存",
        // 自定义信息
        dataType: "none",
      });
      orderItems.length = 0;
    },
  },
  {
    name: "取单",
    count: () => depositReceiptInfo.value.productList.length /* "···" */,
    show: () => true,
    func: () => {
      console.log("取单");

      if (depositReceiptInfo.value.productList.length == 0)
        return refCommonPopup.value.open({
          title: "没有存单记录",
          closeInAfter: 10000,
          content: "",
          type: "",
          // 自定义信息
          dataType: "none",
        });

      // 判断购物车是否有数据，有则提示
      if (orderItems.length > 0) {
        refPopup.value.open({
          title: "购物车已有商品",
          content: "当前购物车已有商品，确定取单覆盖购物车？",
          type: "modal",
          confirmText: "确定",
          cancelText: "取消",
        });
        return;
      }

      confirmPopup();
    },
  },
];

const confirmPopup = () => {
  // 是否验证存单会员与取单会员是否一致 （？）

  const carlist = depositReceiptInfo.value.productList;
  orderItems.length = 0;
  orderItems.push(...carlist);
  isPack.value = depositReceiptInfo.value.isPack;
  refCommonPopup.value.open({
    title: "取单完成",
    closeInAfter: 10000,
    content: `${orderItems.length}个商品已添加到购物车`,
    // 自定义信息
    dataType: "none",
  });
  // 清除 存单记录
  store.commit("shoppingCard/setDepositReceipt", {
    productList: [], // 商品列表
  });
};

const depositReceiptInfo = computed(() => store.getters.depositReceipt);

const getToolBarItemName = computed(() => {
  return (item) => {
    if (typeof item.name === "function") {
      return item.name();
    }
    return item.name;
  };
});

const toolbarItemClick = (item) => {
  if (item.func && typeof item.func === "function") {
    item.func();
  }
};

// 结算

const refPayOrderDialog = ref();
const goCollectPayment = async () => {
  // 禁用购物车
  isMask.value = true;
  panelShow.value = true;

  // 商品详情
  const productDetails = {
    isPack: isPack.value, // 是否打包
    useMember: !!merberInfo.value.customerName, // 是否登录会员
    member: merberInfo.value || {}, // 会员信息 useMember = true 时使用,
    productList: orderItems, // 商品列表
  };

  // 注入数据
  store.commit("shoppingCard/setCurrShoppingCard", productDetails);

  nextTick(() => {
    // 关闭其他面板
    refOrderDialog.value.close();
    // 显示结算支付页面
    refPayOrderDialog.value.open({
      cartlist: orderItems,
      totalPrice: totalPrice.value,
      isPack: isPack.value,
    });

    // 更新客户屏
    openSubScreenByParams({ mode: "standby-mode", money: totalPrice.value, action: "please-pay", payType: "card" });
  });
};

/**
 * 结算完成
 * @param { success | cancel | fail } 回调数据
 */

const refCommonPopup = ref();

const onPayFinish = async (payload) => {
  const { orderId: parentId, amount, money, status, payType, payMerber } = payload.payBean;
  if (status === "success") {
    // 清空购物车
    orderItems.length = 0;

    console.log("收款结束：", payload);
    const modelMoney = Number(money);
    const trueMoney = Number(amount);

    // 根据订单id查询订单详情
    const parentOrderInfo = await getParentOrderInfo(parentId);

    let popupConfig = {};

    // 如果是现金收款，而且收款金额大于应收，则提示找零
    if (payType === "cash" && trueMoney > modelMoney) {
      // 现金支付找零
      console.log("收款金额大于应收，请找零:", amount - money, "元", `${amount} - ${money}`);
      popupConfig = {
        title: "收款成功",
        closeInAfter: 600000,
        // 自定义信息
        dataType: payType,
        giveChange: `${(amount - money).toFixed(2)}`,
      };
      refCommonPopup.value.open(popupConfig);
    } else if (payType === "card" || payType === "face") {
      // 如果当前已登录会员(getMerberInfo 内判断)， 则请求接口查询更新的会员信息, 或者如果支付方式为会员支付，一般会返回会员信息（payMerber）
      const newMerberInfo = await getMerberInfo(parentOrderInfo, payMerber);
      // 会员支付成功提示信息
      popupConfig = {
        title: "会员卡收款成功",
        closeInAfter: 60000,
        // 自定义信息
        dataType: payType,
        // 返回会员信息
        merberInfo: newMerberInfo || {},
      };
    } else {
      // 其他情况显示商户支付成
      popupConfig = {
        title: "收款成功",
        closeInAfter: 5000,
      };
    }

    // 不管何种原因，上组件已发送结束支付时，都可以关闭订单待支付页了，如果不想关闭，应该在对应支付组件中处理，处理不了或处理结束才会通知
    isMask.value = false;
    panelShow.value = false;
    // 显示收款结果弹窗
    refCommonPopup.value.open(popupConfig);
    // 打印小票
    toPrintTick(parentOrderInfo);
  } else if (status === "cancel") {
    console.log("取消支付");
  } else if (status === "fail") {
    console.warn("支付失败");
    // 弹出支付失败提示
    refCommonPopup.value.open({
      title: "支付失败",
      type: "fail",
    });
  } else {
    console.error("支付异常");
    // 弹出支付失败提示
    refCommonPopup.value.open({
      title: "支付异常",
      content: `未知的支付状态 "${status}"`,
      type: "fail",
    });
  }
  // 更新客户屏
  openSubScreen();
};

// 获取订单信息
const getParentOrderInfo = (id) => {
  return new Promise((resolve, reject) => {
    const pam = { parentId: id };
    getBuffetOrderDetailByPrentId(pam)
      .then(({ data, success }) => {
        if (!success || !data || data.length == 0) throw new Error("获取订单信息失败");
        // 注意这个 DetailByPrentId 返回的是订单组， 这里暂时只取第一个订单
        resolve(data[0]);
      })
      .catch((error) => {
        console.error("获取订单信息失败", error);
        resolve(false);
      });
  });
};

// 获取新的会员账户/卡/老人信息
const getMerberInfo = async (orderInfo, payMerber) => {
  return new Promise((resolve, reject) => {
    // 如果当前未登录会员, 并且会员支付未返回会员信息，则直接返回空 (支付之前登录会员，使用会员卡支付，结束之后会显示余额)
    if (!merberInfo.value.customerName && !payMerber?.customerInformationId) return resolve(false);
    const customId = payMerber?.customerInformationId || merberInfo.value.customerInformationId;

    getDetailsByCustomerId(customId)
      .then((data) => {
        if (!data) throw new Error("获取会员账户/卡/老人信息失败");
        // if (!data.customerInfo || !data.cardInfo || !data.accountInfo) throw new Error("获取订单信息失败");
        // 再次处理数据，简化成所需数据
        const { customerInfo, cardInfo, accountInfo } = data;
        resolve({
          name: customerInfo.customerName,
          level: accountInfo.membershipLevelName,
          money: accountInfo.money,
          orderMoney: orderInfo.money,
          discount: orderInfo.money - orderInfo.amountcollected - orderInfo.mealAllowance, // 用分组id查到的里面没有商品列表，所以这直接减算
          helpMoney: orderInfo.mealAllowance,
          payMoney: orderInfo.amountcollected,
        });
      })
      .catch((error) => {
        console.error("获取会员账户/卡/老人信息失败", error);
        resolve(false);
      });
  });
};

// 加算总的会员优惠
const totalDiscount = (goodsList) => {
  console.log("会员优惠计算", goodsList);
  if (!goodsList || !Array.isArray(goodsList)) return 0;
  return goodsList.reduce((pre, cur) => {
    let discount = cur.memberPrice ? (cur.price - cur.memberPrice) * cur.foodNum : 0;
    return pre + discount;
  }, 0);
};

// 加载
const loading = ref(false);

// 是否打包 (1:是 0:否)
const isPack = ref(0);
const onIsPackChange = (checkeds) => {
  isPack.value = checkeds.includes("isPack") ? 1 : 0;
};

// 执行打印
const toPrintTick = async (parentOrderInfo) => {
  try {
    // 查询打印机配置, 参数为 1 则开启打印， 2 为关闭打印
    const { frontDeskPrinting, rearKitchenPrinting } = store.getters.printModule;
    // 计算打印次数 （当前只有一个打印机，如多打印机，需要根据打印机备注的位置打印）
    let printCount = 0;
    [frontDeskPrinting, rearKitchenPrinting].map((v) => {
      if (v == 1) printCount++;
    });
    if (printCount == 0) return;

    // 商家信息
    const { abbreviation } = store.getters.businessInfo;

    // 使用订单id 查询订单详细
    const { data: orderDetails } = await getBuffetOrderDetail({ buffetOrderId: parentOrderInfo.buffetOrderId });

    if (orderDetails.buffetOrderId) {
      // 触发网络打印
      netPrinterPrinting(orderDetails.buffetOrderId)
        .then(({ success, data, msg }) => {
          if (!success) console.error("网络打印失败", { success, data, msg });
        })
        .catch((err) => {
          console.error("网络打印失败", err);
        });
    }

    const goodslist = orderDetails.buffetOrderItemEntityList.map((v) => {
      return {
        foodName: v.foodName,
        number: v.foodNum,
        price: formatMoney(/* v.memberPrice || */ v.price),
        totel: formatMoney(/* v.memberPrice ||  */ v.price * v.foodNum),
      };
    });

    const discount = totalDiscount(orderDetails.buffetOrderItemEntityList);

    const res = {
      orderNo: orderDetails.buffetOrderId,
      merchname: abbreviation,
      opuser: "默认收银员", // TODO 目前没有收银员登录账号，都是登录商家账号
      time: parentOrderInfo.createTime,
      goodslist: goodslist,
      remark: getRemark(orderDetails.buffetOrderItemEntityList),
      fee: formatMoney(parentOrderInfo.amountcollected),
      subsidies: formatMoney(parentOrderInfo.mealAllowance),
      discount: formatMoney(discount),
      total: formatMoney(parentOrderInfo.amountcollected),
    };

    // 打印设备错误数量
    let errcount = 0;

    if (frontDeskPrinting == 1) {
      // 查询打印设置(获取前台后台打印当前模板参数)
      // 将订单信息以固定参数格式处理，输出打印SDK可用的JSON数据
      const temp = store.getters.currentFrontTemplate;
      const printInstance = printorder(res, temp);
      // 查询本地设备列表中类型为 后厨 打印的设备
      const frontDevices = store.getters.usbPrinterListFront;
      if (Array.isArray(frontDevices) && frontDevices.length > 0) {
        // 下单打印小票 需要根据 【打印设置】 中的设备需要打印的设备类型，再从
        // 本地设备列表中获取对应类型的设备id，然后调用打印接口
        for (const device of frontDevices) {
          try {
            await printStartByDevice(printInstance.data, device.path);
          } catch (error) {
            console.error(`设备 ${device.name} 打印小票失败`, error);
            errcount = errcount + 1;
          }
        }
      } else {
        // 打印
        await printStart(printInstance.data);
      }
    }

    if (rearKitchenPrinting == 1) {
      // 查询打印设置(获取前台后台打印当前模板参数)
      // 将订单信息以固定参数格式处理，输出打印SDK可用的JSON数据
      const temp = store.getters.currentRearTemplate;
      const printInstance = printorder(res, temp);
      // 查询本地设备列表中类型为 后厨 打印的设备
      const rearKitchenDevices = store.getters.usbPrinterListRear;
      if (Array.isArray(rearKitchenDevices) && rearKitchenDevices.length > 0) {
        // 下单打印小票 需要根据 【打印设置】 中的设备需要打印的设备类型，再从
        // 本地设备列表中获取对应类型的设备id，然后调用打印接口
        for (const device of rearKitchenDevices) {
          try {
            await printStartByDevice(printInstance.data, device.path);
          } catch (error) {
            console.error(`设备 ${device.name} 打印小票失败`, error);
            errcount = errcount + 1;
          }
        }
      } else {
        // 打印
        await printStart(printInstance.data);
      }
    }

    if (errcount > 0) uni.showToast({ title: `有${errcount}台设备打印小票失败`, icon: "none" });
  } catch (error) {
    console.warn("toPrintTick 打印小票失败", error);
  }
};

/** 循环购物车列表整合备注信息 */
const getRemark = (list) => {
  if (!Array.isArray(list) || list.length == 0) return "";
  return list
    .map((v) => {
      return `${v.foodName}: ${v.remark};`;
    })
    .join("\n");
};

// 取消支付
const cancelPay = () => {
  isMask.value = false;
  panelShow.value = false;
};

onMounted(() => {
  // // 监听添加购物车事件
  uni.$on("cart-item:add", (data) => {
    if (data) {
      // 判断是否已存在该商品
      const index = orderItems.findIndex((item) => item.foodTypeId === data.foodTypeId);
      if (index > -1) {
        orderItems[index].count += 1;
        // 强化显示当前添加的商品
        currSelected.value = orderItems[index];
        return;
      } else {
        data.count = 1;
        orderItems.push(data);
        currSelected.value = orderItems[orderItems.length - 1];
      }
    } else {
      console.log("添加购物车失败");
      uni.showToast({ title: "添加购物车失败", icon: "error" });
    }
  });

  // 监听 面板 关闭事件
  uni.$on("panel:close", () => {
    // 关闭面板 清空当前选择
    panelShow.value = false;
  });

  // 判断顿存单信息是否过期
  // 存单过期 （非当天存单，默认只保存当天，考虑到本地数据可能与网络数据有差异的问题，目前暂无检测存单商品有效接口）
  if (dayjs().format("YYYY/MM/DD") !== dayjs(depositReceiptInfo.value.saveTime).format("YYYY/MM/DD")) {
    // 清除存单
    store.commit("shoppingCard/setDepositReceipt", {
      isPack: 0, // 是否打包
      useMember: false, // 是否登录会员
      member: {}, // 会员信息 useMember = true 时使用,
      productList: [...orderItems], // 商品列表 (...orderItems 取消其引用特性)
      // saveTime: dayjs().format("YYYY/MM/DD HH:mm:ss"), // 存单时间
    });
  }

  // 初始化会员登录信息
});

// 销毁事件
onBeforeUnmount(() => {
  uni.$off("cart-item:add");
  uni.$off("panel:close");
});

/** 会员登录 (读卡 && 刷脸) */

const merberInfo = ref(store.getters.currShoppingCardInfo?.member || {});

const onClickMemberLogin = () => {
  // 判断是否已经登录
  if (merberInfo.value && merberInfo.value.customerInformationId) {
    // 已登录打开信息弹窗
    refMerberInfoPopup.value.open({ title: "会员信息" });
  } else {
    // 未登录弹窗登录
    refMerberLoginPopup.value.open();
    // 未登录 打开读卡器读取进行登录
    // startReadCard();
  }
};

// 登录成功
const onMerberLogin = async ({ type, id, data }) => {
  console.log("会员登录结束", { type, id, data });
  if (data) {
    merberInfo.value = data;

    // 在当前页面会员登陆/登出后需要刷新菜品信息
    uni.$emit("page:pull-downd-refresh");
  }
};

// 退出登录
const clearMember = () => {
  refMerberInfoPopup.value.close();
  merberInfo.value = {};
  uni.showToast({ title: "已退出登录", icon: "none" });
  // 调用设置本地会员信息 (只传需要修改的信息)
  store.commit("shoppingCard/setCurrShoppingCard", {
    useMember: false, // 是否登录会员
    member: {}, // 会员信息 useMember = true 时使用,
  });
  // 在当前页面会员登陆/登出后需要刷新菜品信息
  uni.$emit("page:pull-downd-refresh");
};
const clearMemberOfComPopup = () => {
  refCommonPopup.value.close();
  merberInfo.value = {};
  uni.showToast({ title: "已退出登录", icon: "none" });
  // 调用设置本地会员信息 (只传需要修改的信息)
  store.commit("shoppingCard/setCurrShoppingCard", {
    useMember: false, // 是否登录会员
    member: {}, // 会员信息 useMember = true 时使用,
  });
};

const refMerberLoginPopup = ref();

// 读卡
const refNfcPopup = ref();

const startReadCard = async () => {
  console.log("开始读卡");
  try {
    const card = await refNfcPopup.value.reading();

    console.log("读卡结束", card);
    if (card) {
      // 查询会员信息
      const { data } = await getCustomerInfoByCard({ physicalCardNumber: card });
      if (!data) throw new Error("会员信息不存在");
      merberInfo.value = data;
      uni.showToast({ title: "登录成功", icon: "success" });
      store.commit("shoppingCard/setCurrShoppingCard", {
        useMember: true, // 是否登录会员
        member: data, // 会员信息 useMember = true 时使用,
      });
    }
  } catch (error) {
    console.error("读卡失败", error);
    // 弹出提示
    refCommonPopup.value.open({
      title: "读卡失败",
      content: error.message || "读卡失败",
      type: "fail",
    });
  }
};

const cardInfo = ref({});
const initCardByInfo = async (customerId) => {
  try {
    const { data } = await getCardByCustomerId({ customerId });
    if (data) cardInfo.value = data;
  } catch (error) {
    console.error("查询卡信息失败", error);
  }
};
</script>
<style lang="scss" scoped>
.com-shopping-cart {
  background-color: white;
  font-size: 12rpx;
  display: flex;
  height: 100%;
  position: relative;
  border-radius: 5rpx;

  .shopping-cart-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(224, 224, 224, 0.747);
    z-index: 2;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(1px);

    .mask-icon {
      width: 30rpx;
      height: 30rpx;
    }

    .mask-txt {
      display: block;
      color: grey;
      margin-top: 10rpx;
    }

    ::v-deep .u-button--square {
      border-radius: 3rpx;
    }
  }

  .left-box {
    flex: auto;
    border-right: 1px solid #eee;
    display: flex;
    flex-direction: column;

    .merber-login {
      border-bottom: 1px solid #eee;
      height: 10vh;
      padding: 10rpx;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
    }

    .order-list {
      flex: auto;
      height: 100%;
      overflow-y: scroll;
    }

    .order-item {
      padding: 10rpx;
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      &.active {
        background-color: var(--kui-color-theme-light);
      }

      ._item-name {
        flex: 3;
        font-weight: bold;
      }

      @keyframes fadeIn {
        0% {
          transform: scale(1);
        }
        50% {
          transform: scale(1.2);
        }
        100% {
          transform: scale(1);
        }
      }

      ._item-count {
        flex: 1;
      }

      ._item-price {
        flex: 1;
        color: orange;
      }
    }

    .settlement {
      border-top: 1px solid #eee;
      font-size: 10rpx;

      .total-count {
        margin-right: 10rpx;
      }

      .total-price {
        color: var(--kui-color-theme);
        font-weight: bold;
      }
    }
  }

  .right-box {
    display: flex;
    flex-direction: column;
    justify-content: start;
    align-items: center;
    width: 40rpx;
    padding: 10rpx 0;

    .toolbar-item {
      width: 30rpx;
      height: 30rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 5rpx;
      margin-bottom: 10rpx;
      font-size: 10rpx;
      font-weight: bold;

      .point {
        position: absolute;
        background-color: red;
        color: white;
        padding: 0 2rpx;
        height: 10rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 10rpx;
        border-radius: 3rpx;
        right: -5rpx;
        top: -1rpx;
        font-weight: normal;
      }
    }
  }

  .panel {
    position: absolute;
    left: 100%;
    margin-left: 10rpx;
    z-index: 99;
    height: 100%;

    .panel-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.1);
      filter: blur(20px);
    }

    .col-layout {
      position: relative;
      box-shadow: 2rpx 2rpx 10rpx #c0c0c0;
      border-radius: 5rpx;
      align-self: flex-start;
      z-index: 2;

      &.not-shadow {
        box-shadow: none;
      }
    }
  }
}

.btns-item {
  background-color: #efefef;
  padding: 5rpx 20rpx;
  border-radius: 5rpx;
  margin: 0rpx 15rpx;
  font-size: 12rpx;

  &.confirm {
    color: white;
    background-color: orangered;
  }

  .btns-item-txt {
    font-size: 10rpx;
    padding: 5rpx 15rpx;
  }

  ::v-deep .u-button {
    padding: 2rpx 20rpx;
  }
}
</style>
